

from ctypes import create_string_buffer
from cStringIO import StringIO
import struct
import time

class Pkt:
  def __init__(self):
    self.buffer = StringIO()
    self.readPos = 0

  def PutInt(self, val):
    buffer = self.buffer
    str = struct.pack("i", val)
    buffer.write(str)

  def PutShort(self, val):
    buffer = self.buffer
    str = struct.pack("h", val)
    buffer.write(str)

  def PutUTF(self, val):
    buffer = self.buffer
    str_len = len(val)
    str = struct.pack("h%ds"%str_len, str_len, val)
    buffer.write(str)

  def GetInt(self):
    buffer = self.buffer
    val = struct.unpack_from("i", buffer.getvalue(), self.readPos)
    self.readPos += 4

    return val[0]

  def GetShort(self):
    buffer = self.buffer
    val = struct.unpack_from("h", buffer.getvalue(), self.readPos)
    self.readPos += 2

    return val[0]

  def GetUTF(self):
    buffer = self.buffer
    strlen = struct.unpack_from("h", buffer.getvalue(), self.readPos)
    strlen = strlen[0]
    val = struct.unpack_from("%ds"%strlen, buffer.getvalue(), self.readPos + 2)
    self.readPos += strlen + 2

    return val[0]

  def Print(self):
    buffer = self.buffer
    print repr(buffer.getvalue())


if __name__ == '__main__':
  print time.time()
  pkt = Pkt()
  pkt.PutInt(2)
  pkt.PutShort(3)
  pkt.PutUTF("hello")
  pkt.Print()
  print pkt.GetInt()
  print pkt.GetShort()
  print pkt.GetUTF()
  print time.time()
